import { useState, useEffect, useCallback, useMemo } from 'react'
import { View, Text } from '@tarojs/components'
import Card from '../component/card'
import Loading from '../component/load'
import Empty from '../component/empty'
import Taro, { setPageInfo, useTabItemTap } from '@tarojs/taro'
import LgSelepicker from '@/pages/components/selePick'
import { getStorage } from '@/pages/components/utils/index'
import LgRefreshPage from '@/pages/components/refreshPage'
import LgSearch from '@/pages/components/searchInput'
import { LgSlide } from '@/pages/components/slide'
import { HttpGet, HttpPost, HttpDelete, HttpPut } from '@/network/servers'
import Utils from '@/utils/index'
import _ from 'lodash'
import { getBrowserController } from '@/pages/components/utils'
import { connect, useDispatch } from "react-redux";
import { LgPopLayer } from '@/pages/components/popLayer'
import { LgTabs, LgTab } from '@/pages/components/tabs'
import LgCheckbox from '@/pages/components/checkbox'
import SearchPageComp from '../searchPageComp'
import './index.scss'
const storage = getStorage()
const {
  getNowToken,
  recentDateStr,
  replaceHost,
  useGetIsMapArray,
  getTimeAgo,
} = Utils

var wx = require('weixin-js-sdk')

const browserController = getBrowserController()
let InfoObj = {} as any

function App(props) {

  const {
    userInfo,
    env,
    lg_ic,
    baseUrl,
    mainServer,
    systemInfo1,
    isAdvancedAdmin,
    isManage,
  } = props

  const [allCount, setAllCount] = useState(0)   //总数
  const [pullCount, setPullCount] = useState(1)
  const [newsList, setNewsList] = useState<any>([])
  const [newsList2, setNewsList2] = useState<any>([])
  const [totalPage, setTotalPage] = useState(0)
  const [loadVisible, setLoadVisible] = useState(true)
  const [keyword, setKeyword] = useState('')
  const [systemInfo, setSystemInfo] = useState(systemInfo1)
  const [h, setH] = useState('')

  const [statusList, setStatusList] = useState([{
    key: '',
    name: '全部状态'
  },
  {
    key: '1',
    name: '已发布'
  },
  {
    key: '0',
    name: '未发布'
  },
  ])
  const [typeList, setTypeList] = useState<any>([])
  const [currentStatus, setCurrentStatus] = useState('')
  const [currentType, setCurrentType] = useState('')
  const [isSearch, setIsSearch] = useState(false) //是否展示搜索框
  const [isOpen, setIsOpen] = useState(false) //是否筛选
  const [checkNum, setCheckNum] = useState(0);

  let UserType = storage.get('UserType') || userInfo.userType

  const getToken = () => {
    if (Utils.getQueryVariable('env') === 'weapp') {
      return Utils.getQueryVariable('lg_tk')
    } else {
      return storage.get('token') || Utils.getQueryVariable('lg_tk')
    }
  }

  const getShowThisMsg = (item) => {  //获取当前待办在此环境是否展示
    if (Taro.getInWebview()) {  //小程序环境
      switch (String(item.receiverType)) {
        case '0':
        case '3':
        case '5':
          return true
        default:
          return false
      }
    } else {
      switch (String(item.receiverType)) {
        case '0':
        case '2':
        case '4':
        case '6':
          return true
        default:
          return false
      }
    }
  }

  const getBasicInfo = () => {
    HttpGet({
      url: 'api/news/type/send/type/list',
      data: {
        eduId: userInfo.eduId,
      }
    }).then((result) => {
      let typeList = result.data
      console.log(systemInfo, 'systemInfo');

      if (systemInfo.beEdu == '1') {
        typeList.unshift(
          {
            newsTypeId: '0',
            newTypeName: '校园资讯',
            schoolId: storage.get('schoolId') || userInfo.eduId,
          })
      }
      typeList.unshift({
        newsTypeId: '',
        // newTypeName: '全部类型',
        newTypeName: '全部',
        eduId: storage.get('schoolId') || userInfo.eduId,
      })
      setTypeList(typeList)
    })
  }

  // 获取新闻资讯列表
  const getNewsList = (n = 1) => {
    console.log(userInfo)
    // 获取待办事项总数
    HttpGet({
      url: `api/news/list/page`,
      data: {
        pageNum: 1,
        pageSize: 10 * n,
        keyWord: keyword,
        // userId: userInfo.userId,
        typeId: currentType,
        // schoolId: storage.get('schoolId') || Utils.getQueryVariable('schoolId'),
        // 2023-09-14处理小程序多学校问题
        eduId: userInfo.eduId,
        releaseStatus: isManage === 0 ? 1 : currentStatus,
        sortType: checkNum,
      },
      load: true
    }).then((result) => {
      if (result.code == '200') {
        if (keyword == '') {
          closeSearch();
        }
        const info = result.data
        // let arr = [] as any
        // info && info.forEach((item) => {
        //   console.log(item);

        //   arr.push({
        //     title: item.msgSourceName,
        //     content: item.msgPushContent,
        //     startTime: item.msgPushTime,
        //     endTime: item.msgPushExpire,
        //     ...item
        //   })
        // })

        setNewsList(info)
        setAllCount(info?.length)
        setTotalPage(Math.ceil(Number(result.total) / 10))
        setLoadVisible(false)
        setNewsList2([])
      }
    })
  }

  // 获取搜索中的新闻资讯列表
  const getNewsList2 = (value) => {
    console.log('????')
    if (!value) {
      return
    }
    // 获取待办事项总数
    HttpGet({
      url: `api/news/list/page`,
      data: {
        pageNum: 1,
        pageSize: 10 * 1,
        keyWord: value,
        typeId: currentType,
        eduId: userInfo.eduId,
        releaseStatus: isManage === 0 ? 1 : currentStatus,
        sortType: checkNum,
      },
      load: true
    }).then((result) => {
      if (result.code == '200') {
        // if (keyword == '') {
        //   closeSearch();
        // }
        const info = result.data
        setNewsList2(info)
      }
    })
  }
  const jumpWeapp = (appId, path) => {
    try {
      browserController.navigateToMiniProgramForWebview(wx, {
        appId,//必传 跳转小程序唯一标识
        path,//必传 跳转后初始页面路径
        extraData: {},
        envVersion: 'release',//必传 跳转小程序的版本
      })
    } catch (err) {
      Taro.showToast({ title: err, icon: 'none' })
    }
  }

  //路由返回当前页面并刷新
  if (isManage === 1) {
    Taro.useDidShow(() => {
      setPullCount(1)
      setTimeout(() => {
        getNewsList()
        getBasicInfo()
      }, 200);
      // window.location.reload();
    })
  }

  // 点击事件
  const toLink = (item) => {
    console.log(userInfo, 'userInfo');

    if (item.newsId && item.releaseStatus == 1) {
      if (Utils.getQueryVariable('isManage')) {
        Taro.navigateTo({
          url: '/pages/newsInfoApp/newsDetail/index?newsId=' + item.newsId + '&from=home' + `&lg_tk=${storage.get('token')}&isManage=1`
        })
      } else {
        Taro.navigateTo({
          url: '/pages/newsInfoApp/newsDetail/index?newsId=' + item.newsId + '&from=home' + `&lg_tk=${storage.get('token')}`
        })
      }
    }
    else {
      if (item.userId !== userInfo.userId && ((userInfo.userClass != '2' && userInfo.userClass != '4'))) {
        Taro.showToast({
          title: '只能编辑自己发布的资讯！',
          icon: 'none',
          duration: 2000
        })
        return;
      }
      goCreate(item)
    }
  }

  // 跳转发布页面
  const goCreate = (data) => {
    let url = '/pages/newsInfoApp/createNews/index'
    if (data) {
      url += '?id=' + data.newsId
      // url += '?id=' + data.newsId + ' &lg_tk=' + Utils.getQueryVariable('lg_tk') + '&lg_ic=' + Utils.getQueryVariable('lg_ic')
    }
    Taro.navigateTo({
      url
    })
  }


  // 状态选择
  const handleStatus = (data) => {
    setCurrentStatus(data.key)
  }

  //类型选择
  const handleType = (data) => {
    setCurrentType(data.newsTypeId)
  }

  // 搜索变化
  const searchHandle = _.debounce((value) => {
    setKeyword(value.trim())
  }, 500)

  const searchHandle2 = _.debounce((value) => {
    // setKeyword(value.trim())
    setH(value)
    getNewsList2(value)
  }, 500)

  //关闭搜索栏
  const closeSearch = _.debounce(() => {
    setIsSearch(false);
  }, 500)


  // 无限刷新
  const onPull = () => {
    if (totalPage > pullCount) {
      setPullCount(pullCount + 1)
      getNewsList(pullCount + 1)
    } else {
      Taro.showToast({
        title: '到底啦',
        icon: 'none'
      })
    }
  }
  // 下拉刷新
  const onDown = () => {
    getNewsList()
    setTimeout(() => {
      Taro.showToast({
        title: '刷新成功'
      })
    }, 500)
  }


  useEffect(() => {
    // if ((UserType != '0' && isAdvancedAdmin == 0) && isManage === 0) {
    if (isManage === 0) {
      setCurrentStatus('1')
    }
    getNewsList()
  }, [currentStatus, currentType, keyword, isAdvancedAdmin, checkNum])

  useEffect(() => {
    getBasicInfo()
  }, [])

  const handleDel = (item: any) => {
    console.log(item.newsId, 'newsId1111');

    Taro.showModal({
      title: '提示',
      content: '是否删除所选资讯',
      success: function (res) {
        if (res.confirm) {
          HttpDelete({
            url: 'api/news/manage/delete?newsId=' + item.newsId,
          }).then((result) => {
            getNewsList()
            Taro.showToast({
              title: '删除成功',
              duration: 2000,
              mask: true
            })
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  }

  const callBack = (item) => {
    console.log(item.newsId, 'newsId12');
    Taro.showModal({
      title: '提示',
      content: '确定要撤回该条资讯吗？',
      success: function (res) {
        if (res.confirm) {
          HttpPut({
            url: 'api/news/manage/callBack?newsId=' + item.newsId,
            // data: {
            //   newsId: item.newsId,
            // }
          }).then((result) => {
            getNewsList()
            Taro.showToast({
              title: '撤回成功',
              duration: 2000,
              mask: true
            })
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  }
  const choTab = (value, key) => {
    let currentType = { newsTypeId: '', newTypeName: '全部' }
    useGetIsMapArray(typeList) && typeList.forEach(item => {
      if (item.newTypeName === key) {
        currentType = item
      }
    })
    setPullCount(1)
    setCurrentType(currentType.newsTypeId)
  }

  const handleLayer = useCallback(() => {
    setIsOpen(!isOpen);
  }, [isOpen]);

  const handleCheck = useCallback((_checkNum) => {
    setCheckNum(_checkNum);
  }, []);

  const childenDom = () => {
    console.log(newsList2)
    console.log(h)
    return (
      <View>
        {
          newsList2.length > 0 ? newsList2.map(i => {
            console.log(i.newsTitle.indexOf(h))
            let indexH = i.newsTitle.indexOf(h)
            return (
              <View onClick={() => { toLink(i) }} className='itemList'>{i.newsTitle.slice(0, indexH)} <span style={{ color: '#ff7d27' }}>{i.newsTitle.slice(indexH, indexH + h.length)}</span> {i.newsTitle.slice(indexH + h.length)}</View>
            )
          }) : ''
        }
      </View>
    )
  }
  return (
    <View className='todo_contanier'>
      <View className="todo_option">
        {/* 更新UI */}
        <View>
          <LgSelepicker
            type='B'
            id='sele2'
            className='left'
            dataList={typeList}
            changeSele={handleType}
            attr='newTypeName'
          />
          {
            // UserType == '0' || isAdvancedAdmin == 1 || isManage === 1 ?
            isManage === 1 ?
              <LgSelepicker
                type='B'
                id='sele1'
                className='left'
                dataList={statusList}
                changeSele={handleStatus}
                attr='name'
              /> : ''
          }
        </View>
        {/* {
          isSearch ?
            <View className='my_ipt'>
              <LgSearch
                value={keyword}
                onConfirm={(value) => { setKeyword(value.trim()) }}
                placeholder='请输入...'
                onInput={searchHandle}
              />
            </View> : */}
        <View className='my_ipt'>
          <View className='my_search_icon' onClick={() => setIsSearch(true)}></View>
          <View className='my_screen_icon' onClick={() => setIsOpen(true)}></View>
        </View>
        {/* } */}
      </View>
      {/* {
        isSearch ? */}
      <SearchPageComp
        setDataList={() => {
          setNewsList2([])
        }}
        placeholder={'搜索部门通知标题'}
        visible={isSearch}
        dataList={newsList2}
        loading={false}
        childrenDom={childenDom()}
        setVisible={() => {
          setIsSearch(false)
        }}
        setWords={(h) => { searchHandle2(h) }}></SearchPageComp>
      {/* //        : ''
      // } */}
      <LgPopLayer
        position="bottom"
        isOpen={isOpen}
        showLayer={handleLayer}
        showClose
        title="排序筛选"
      >
        <View className="sort_view">
          <View className="sort_center">
            <LgCheckbox
              className="lg-checkbox"
              type="A"
              value={checkNum === 0}
              onClick={handleCheck.bind(null, 0)}
              children={'时间由近到远排序'}
            />
          </View>
          <View className="sort_center">
            <LgCheckbox
              className="lg-checkbox"
              type="A"
              value={checkNum === 1}
              onClick={handleCheck.bind(null, 1)}
              children={'时间由远到近排序'}
            />
          </View>
          <View className="sort_center">
            <LgCheckbox
              className="lg-checkbox"
              type="A"
              value={checkNum === 2}
              onClick={handleCheck.bind(null, 2)}
              children={'阅读次数升序排序'}
            />
          </View>
          <View className="sort_center">
            <LgCheckbox
              className="lg-checkbox"
              type="A"
              value={checkNum === 3}
              onClick={handleCheck.bind(null, 3)}
              children={'阅读次数降序排序'}
            />
          </View>
        </View>
      </LgPopLayer>
      {/* <View className='tab_view'>
        <LgTabs
          onClick={choTab}
          showIcon
          customIcon={<></>}
          default={0}
          className='tab_back'
        >
          {
            typeList.map((item, index) => {
              return (
                <LgTab
                  key={index}
                  count={0}
                  title={item.newTypeName}
                />
              )
            })
          }
        </LgTabs>
      </View> */}
      <Loading mode="center" content="加载中..." isOpened={loadVisible}></Loading>
      <LgRefreshPage
        className='index'
        onPull={onPull}
        onDown={onDown}
        downText={['下拉刷新', '释放刷新']}
        pullText={['上拉加载更多', '释放加载更多']}>
        {
          newsList?.length > 0 ?
            newsList.map((item, index) => {
              if (item.beEduPush == '1' && item.newsCoverPath != '') {
                if (!item.newsCoverPath.toLowerCase().includes('http')) {
                  item.newsCoverPath = systemInfo.governmentWebUrl + '/' + item.newsCoverPath
                }
              }
              // 2024-2-23适配首页卡片小程序图片跨域开裂
              // 要展示的 HTML 字符串
              var htmlString = item.newsContent

              // 使用正则表达式匹配 img 标签的 src 属性并替换
              var modifiedHtml = htmlString.replace(/(<img[^>]+src=")([^"]+)("[^>]*>)/gi, function (match, p1, p2, p3) {
                // 根据条件修改 src 属性
                if (Utils.getQueryVariable('env') === 'weapp' && item.beEduPush == '1') {
                  return p1 + replaceHost(p2, systemInfo.governmentWebUrl) + p3;
                } else if (Utils.getQueryVariable('env') === 'weapp') {
                  return p1 + replaceHost(p2, baseUrl) + p3;
                } else {
                  return match; // 保持不变
                }
              });

              // if (getShowThisMsg(item)) {

              return (
                <LgSlide
                  data={(item.releaseStatus == '0' && ((((item.userId == storage.get('UserID') || item.userId == userInfo.userId)
                    || (userInfo.userClass == '2' || userInfo.userClass == '4')) && UserType == '0') || isAdvancedAdmin == 1 || isManage === 1)) && item.beEduPush != '1' ? [
                    {
                      text: '编辑',
                      className: 'edit',
                      onClick: () => goCreate(item)
                    },
                    {
                      text: '删除',
                      className: "del",
                      onClick: () => handleDel(item)
                    }
                    // ] : (item.releaseStatus == '1' && (item.userId == storage.get('UserID') || item.userId == userInfo.userId)) && item.beEduPush != '1' ? [
                  ] : (item.releaseStatus == '1' && ((item.userId == storage.get('UserID') || item.userId == userInfo.userId)
                    || (userInfo.userClass == '2' || userInfo.userClass == '4'))) && isManage === 1 && item.beEduPush != '1' ? [
                    {
                      text: '撤回',
                      className: "del",
                      onClick: () => callBack(item)
                    }
                  ] : []}
                  canSlide
                  key={(userInfo.userType == '0' || isAdvancedAdmin == 1 || isManage === 1) ? (item.newsId + item.releaseStatus) : index}
                >
                  <Card
                    type='F'
                    key={index}
                    title={item.newsTitle}
                    publisher={item.userId}
                    userType={userInfo.userType}
                    userName={item.userName}
                    // content={item.newsContent}
                    content={modifiedHtml}
                    releaseTime={getTimeAgo(item.releaseTime)}
                    status={item.releaseStatus}
                    toLink={() => { toLink(item) }}
                    newsCoverPath={Utils.getQueryVariable('env') === 'weapp' && item.beEduPush == '1' ? replaceHost(item.newsCoverPath, systemInfo.governmentWebUrl) : Utils.getQueryVariable('env') === 'weapp' ? replaceHost(item.newsCoverPath, baseUrl) : item.newsCoverPath}
                    newsTypeName={item.newsTypeName}
                    isAdvancedAdmin={isAdvancedAdmin}
                    isManage={isManage}
                    index={index}
                    readCount={item.readCount}
                  />
                </LgSlide>

              )
              // }
            }) : !loadVisible ? <Empty /> : ''
        }
      </LgRefreshPage>
      {/* 创建+ */}
      {
        // UserType == '0' || isAdvancedAdmin == 1 || isManage === 1 ?
        isManage == 1 ?
          <><View className='create' onClick={() => goCreate('')}></View>
            <i className='create-shadow'></i></>
          : ''
      }

    </View>
  )
}


const mainProps = ({ commonData }) => {
  // console.log(commonData, 'commonData');

  return {
    userInfo: commonData.userInfo,
    env: commonData.env,
    baseUrl: commonData.baseUrl,
    mainServer: commonData.mainServer,
    lg_ic: commonData.lg_ic,
    systemInfo1: commonData.systemInfo,
    isAdvancedAdmin: commonData.advancedAdmin,
    isManage: commonData.isManage,
  }
}

export default connect(mainProps)(App)